package org.csu.mypetstore.Controller;

import org.apache.ibatis.annotations.Param;
import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.domain.Log;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CategortService;
import org.csu.mypetstore.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    CartService cartService;
    @Autowired
    CategortService categortService;
    @Autowired
    LogService logService;

    @RequestMapping("/ViewCart")
    public String ViewCart(HttpServletRequest req, Cart cart, Model model) {
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        List<Cart> cartList = new ArrayList<Cart>();
        if (account != null) {
            String logInfo = " 查看购物车 " + cart;
            logService.insertLogInfo(account.getUsername(), logInfo);
            cartList = cartService.getCartByusername(account.getUsername());
            int cartListsize = cartList.size();
            if (cart == null) {
                cart = new Cart();
            }
            model.addAttribute("cart", cart);
            BigDecimal subtoatl = new BigDecimal(0);
            int i = 0;
            while (i < cartListsize) {
                subtoatl = subtoatl.add(cartList.get(i).getTotal());
                i++;
            }
            model.addAttribute("cartList", cartList);
            model.addAttribute("cartListsize", cartListsize);
            session.setAttribute("cartListsize", cartListsize);
            session.setAttribute("cartList", cartList);
            session.setAttribute("subTotal", subtoatl);
            model.addAttribute("subTotal", subtoatl);
            return "/cart/Cart";
        } else {
            return "/account/SignonForm";
        }
    }

    @RequestMapping("/ViewCheckout")
    public String ViewCheckout() {

        return "/cart/Checkout";
    }

    @RequestMapping("/AddItemtoCart")
    public String AddItemtoCart(HttpServletRequest req, Model model, Cart cart) {
        String workingItemId;
        int cartListsize;
        BigDecimal subtoatl;
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        workingItemId = req.getParameter("workingItemId");
        Item item = categortService.getItem(workingItemId);
        if (account != null) {
            String username = account.getUsername();
            String logInfo = " 添加物品 " + item + " 到购物车";
            logService.insertLogInfo(account.getUsername(), logInfo);
            if (cart == null) {
                cart = new Cart();
            }
            if (cartService.isExit(username, workingItemId) > 0) {
                cart = cartService.getCart(username, workingItemId);
                try {
                    cart.setQuantity(cart.getQuantity() + 1);
                    cart.setTotal(cart.getListprice().multiply(BigDecimal.valueOf(cart.quantity)));
                    cartService.Updatecart(username, workingItemId, cart);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            } else {
                boolean isInStock = categortService.isItemInStock(workingItemId);
                cart.addItem(item, isInStock);
                cart.setItemid(item.getItemId());
                cart.setProductid(item.getProductId());
                cart.setDescription(categortService.getProduct(item.getItemId()).getDescn());
                cart.setListprice(item.getListPrice());
                cart.setQuantity(1);
                cart.setStock(isInStock);
                cart.setTotal(cart.getListprice().multiply(BigDecimal.valueOf(cart.quantity)));
                cartService.insertintocart(cart, account.getUsername());
            }
            List<Cart> cartList = new ArrayList<>();
            cartList = cartService.getCartByusername(username);
            cartListsize = cartList.size();
            subtoatl = new BigDecimal(0);
            int i = 0;
            while (i < cartListsize) {
                subtoatl = subtoatl.add(cartList.get(i).getTotal());
                i++;
            }
            model.addAttribute("cartList", cartList);
            model.addAttribute("cartListsize", cartListsize);
            model.addAttribute("cart", cart);
            model.addAttribute("subTotal", subtoatl);

            session.setAttribute("cartList", cartList);
            session.setAttribute("cartListsize", cartListsize);
            session.setAttribute("cart", cart);
            session.setAttribute("subTotal", subtoatl);
            return "/cart/Cart";
        } else {
            return "account/SignonForm";
        }
    }

    @RequestMapping("/UpdateCartJS")
    public void UpdateCartJS(HttpServletRequest request, HttpServletResponse response) {
        List<Cart> cartList;
        BigDecimal subtoatl;
        //从对话中，获取购物车
        HttpSession session = request.getSession();
        Account account = (Account) session.getAttribute("account");
        String username = account.getUsername();
        cartList = cartService.getCartByusername(username);
        String[] strify = (String[]) request.getParameterValues("quantity");
        String[] nq = new String[(strify[0].length() - 1)];
        nq = strify[0].split(",");
        int i = 0;
        while (i < cartList.size()) {
            //产品数量增加
            Cart cart = (Cart) cartList.get(i);
            String itemId = cart.getItemid();
            try {
                cart.setQuantity(Integer.parseInt(String.valueOf(nq[i])));
                cart.setTotal(cart.getListprice().multiply(BigDecimal.valueOf(Integer.parseInt(String.valueOf(nq[i])))));
                cartService.Updatecart(username, itemId, cart);
                if (Integer.parseInt(String.valueOf(nq[i])) < 1) {
                    cartService.Delete_By_Username_and_Itemid(username, itemId);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            i++;
        }

        subtoatl = new BigDecimal(0);
        int k = 0;
        while (k < cartList.size()) {
            subtoatl = subtoatl.add(cartList.get(k).getTotal());
            k++;
        }
        session.setAttribute("cartList", cartList);
        String quantityAll = "";
        int j = 0;
        while (j < cartList.size()) {
            //产品数量增加
            Cart cart = (Cart) cartList.get(j);
            int quantity2 = cart.getQuantity();
            BigDecimal total = cart.getListprice().multiply(BigDecimal.valueOf(quantity2));
            quantityAll += quantity2 + "," + total + ",";
            j++;
        }
        quantityAll += subtoatl;
        response.setContentType("text/xml");
        try {
            PrintWriter out = response.getWriter();
            out.write(quantityAll);
            session.setAttribute("subTotal", subtoatl);
        }catch (Exception e){

        }
    }
    @RequestMapping("/DeleteItem")
    public String DeleteItem(HttpServletRequest req, Model model) {
        String workingItemId;
        Cart cart;
        BigDecimal subtoatl;
        workingItemId = req.getParameter("itemid");
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        String logInfo = logService.logInfo(" ") + workingItemId + " 已从购物车中移除";
        cartService.Delete_By_Username_and_Itemid(account.getUsername(), workingItemId);
        List<Cart> cartList = new ArrayList<>();
        if (account != null)
            cartList = cartService.getCartByusername(account.getUsername());
        int cartListsize = cartList.size();
        subtoatl = new BigDecimal(0);
        int k = 0;
        while (k < cartList.size()) {
            subtoatl = subtoatl.add(cartList.get(k).getTotal());
            k++;
        }
        session.setAttribute("subTotal", subtoatl);
        session.setAttribute("cartList", cartList);
        session.setAttribute("cartListsize", cartListsize);
        model.addAttribute("subTotal", subtoatl);
        model.addAttribute("cartList", cartList);
        model.addAttribute("cartListsize", cartListsize);
        return "/cart/Cart";
    }

}